#include <pvm3.h>

#include "job.h"
#include <string.h>

#define NB_JOB 400;

struct job * get_job(unsigned long max)
{
  static unsigned long current_job = 1;
  
  if(current_job == max/NB_JOB)
    {
      printf("no more jobs");
      return NULL;
    }
  else
    {
      struct job * new_job = malloc(sizeof(struct job));
      new_job->init = current_job*max/NB_JOB;
      new_job->end = (current_job+1)*max/NB_JOB;
      current_job++;
      return new_job;
    }
} 

char *convert(unsigned long deb)
{
  char * str1 = "";
  char * str2 = "";
  unsigned long res = deb%26;
  unsigned long quotient = (deb-res)/26;
  char a;
  int k=0;
  while(quotient!=1)
    {
      a = 'a' + res;
      res = quotient%26;
      strcat(str1,&a);
      quotient /= 26;
      k++;
    }
  int i;
  for (i=0;i<k;i++)
    str2[i]=str1[k-i-1];
  return str2;
}


void * waiting_loop(void * A)
{
 
  while (1)
    {
      struct job * new_job = get_job(pow(26,size_max));
      if (new_job == NULL)
	{
	  return NULL;
	}
      char * str1 = convert(new_job->init);
      char * str2 = convert(new_job->end);
      int bufid = pvm_recv(-1,-1);
      int bytes,msgtag,tid;
      pvm_bufinfo(bufid,&bytes,&msgtag,&tid);
      if (msgtag == 1)
	{
	  pvm_initsend(PvmDataDefault);
	  strcat(str1," ");
	  strcat(str1,str2);
	  pvm_pkstr(str1);
	  pvm_send(tid,1);
	}
      else
	{
	  if (msgtag == 2)
	    {
	      printf("Le processus n°%d a trouvé le mdp\n",tid);  
	      int i;
	      for (i=0;i<nb_slave;i++)
		{
		  pvm_kill(tids[i]);
		}
	      res = 1;
	      return NULL;
	    }
	}
    }
  return NULL;
}


int main(int argc,char*argv[])
{
  if (argc < 3)
    {
      printf("expected slave_nbre | psswd | size_max");
    }
  nb_slave = atoi(argv[1]);
  size_max = atoi(argv[3]);
  tids = malloc(sizeof(int));
  res = 0;

  pthread_t waiting_thread;
  pthread_create(&waiting_thread,NULL,waiting_loop,NULL);
  
  pthread_join(waiting_thread,NULL);
  if (res != 1)
    {
      printf("Password not found");
    }
  return EXIT_SUCCESS;
}

